/*
 *
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: ViewHandlerFactory.java
 *   @Date: 11/29/18 3:21 PM
 *   @Author: chenjun
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 *
 */

package io.bhex.baselib.adapter;

import android.support.v4.util.ArrayMap;

import java.util.Map;

import io.bhex.baselib.utils.Assert;
import io.bhex.baselib.utils.DebugLog;

class ViewHandlerFactory {
    /**
     * 缓存已存在的handler
     */
    private static Map<String, IViewHandler> mHandlerMap = new ArrayMap<>();

    /**
     * 通过类名动态加载创建、加载对应的类对象
     *
     * @param viewHandlerClazz
     * @return
     */
    public static IViewHandler getViewHandler(String viewHandlerClazz) {
        IViewHandler result = mHandlerMap.get(viewHandlerClazz);

        if (result == null) {
            try {
                Class clazz = Class.forName(viewHandlerClazz);

                Assert.judge(IViewHandler.class.isAssignableFrom(clazz), "处理类必须实现IViewHandler接口");

                result = (IViewHandler) clazz.newInstance();
                mHandlerMap.put(viewHandlerClazz, result);
            } catch (Exception e) {
                DebugLog.e(e);
            }
        }

        if (result == null)
            throw new RuntimeException("IViewHandler创建失败:" + viewHandlerClazz);

        return result;
    }
}
